﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Mars.Got;

namespace Yoozoo.Core.Common
{
    [Serializable]
    public class QualitySetting
    {
        public QualityEnum Quality = QualityEnum.None;
    }

    public class QualityListenerMono : MonoBehaviour, IQualityListener
    {
        public string markString;

        protected virtual void OnEnable()
        {
            if (QualityManager.Inst)
            {
                QualityManager.Inst.AddQualityListener(this);
            }
        }

        protected virtual void OnDisable()
        {
            if (QualityManager.Inst)
            {
                QualityManager.Inst.RemoveQualityListener(this);
            }
        }
        
        public virtual void OnChangeQuality(QualityEnum quality)
        {
            
        }
    }
    
    public class QualityListenerMono<T>: QualityListenerMono
        where T : QualitySetting
    {
        [SerializeField]
        protected List<T> QualitySettings;

        [SerializeReference]
        private T currentQualitySetting;

        public T CurrentQualitySetting => currentQualitySetting;

        protected virtual void Awake()
        {
            
        }

        public override void OnChangeQuality(QualityEnum quality)
        {
            var qualitySetting = GetQualitySetting(quality);
            if (qualitySetting!=null)
            {
                ChangeQualitySetting(qualitySetting);
            }
            else
            {
                //UnityEngine.Debug.LogError($"{typeof(T) }没有这个质量等级设置 {quality}");
            }
            currentQualitySetting = qualitySetting;
        }
        
        protected virtual T GetQualitySetting(QualityEnum quality)
        {
            if (QualitySettings!=null)
            {
                for (int i = 0; i < QualitySettings.Count; i++)
                {
                    if (QualitySettings[i].Quality == quality)
                    {
                        return QualitySettings[i];
                    }
                }
            }

            return null;
        }
        
        public virtual void ChangeQualitySetting(T qualitySetting)
        {
            
        }

#if UNITY_EDITOR
        private void OnValidate()
        {
            if (QualitySettings!=null)
            {
                QualitySettings.Sort((a, b) =>
                {
                    return a.Quality - b.Quality;
                });
            }
            
            OnSettingValidate();
        }

        protected virtual void OnSettingValidate()
        {
            
        }
        
#endif
    }
}